#!/bin/sh
# @configure_input@
#
# Script to run a command or shell inside a chroot environment
# prebuilt with the dj_make_chroot script.
#
# Part of the DOMjudge Programming Contest Jury System and licensed
# under the GNU GPL. See README and COPYING for details.

# Abort when a single command fails:
set -e

cleanup() {
    # Unmount things on cleanup
    umount -f "$CHROOTDIR/proc" >/dev/null 2>&1  || /bin/true
    umount -f "$CHROOTDIR/sys" >/dev/null 2>&1  || /bin/true
    umount -f "$CHROOTDIR/dev/pts" >/dev/null 2>&1  || /bin/true
}
trap cleanup EXIT

# Default directory where the chroot tree lives:
CHROOTDIR="@judgehost_chrootdir@"

usage()
{
	cat <<EOF
Usage: $0 [options]... [command]
Runs <command> inside the prebuilt chroot environment. If no command is
given, then an interactive shell inside the chroot is started.

Options:
  -d <dir>    Directory of the prebuild chroot (if not default).
  -h          Display this help.

This script must be run as root. It mounts proc, sysfs and devpts
before starting the chroot, and unmounts those afterwards. This script
can be used, for example, to upgrade or install new packages in the
chroot:

  sudo dj_run_chroot "apt update && apt upgrade"

If you want to install local packages, make sure to first copy those
into the chroot tree, and then e.g. run:

  sudo dj_run_chroot "dpkg -i /path/inside/chroot/package_x.y.z_amd64.deb"

EOF
}

error()
{
    echo "Error: $*"
    echo
    usage
    exit 1
}

# Read command-line parameters:
while getopts 'd:h' OPT ; do
	case $OPT in
		d) CHROOTDIR=$OPTARG ;;
		h) SHOWHELP=1 ;;
		\?) error "Could not parse options." ;;
	esac
done
shift $((OPTIND-1))

if [ -n "$SHOWHELP" ]; then
	usage
	exit 0
fi

if [ $# -eq 0 ]; then
	INTERACTIVE=1
fi

if [ "$(id -u)" != 0 ]; then
    echo "Warning: you probably need to run this program as root."
fi

[ -z "$CHROOTDIR" ] && error "No chroot directory given nor default known."
[ -d "$CHROOTDIR" ] || error "Chrootdir '$CHROOTDIR' does not exist."

cd "$CHROOTDIR"
CHROOTDIR="$PWD"

#rm -f "$CHROOTDIR/etc/resolv.conf"
#cp /etc/resolv.conf /etc/hosts /etc/hostname "$CHROOTDIR/etc" || true
#cp /etc/ssl/certs/ca-certificates.crt "$CHROOTDIR/etc/ssl/certs/" || true
#cp -r /usr/share/ca-certificates/* "$CHROOTDIR/usr/share/ca-certificates" || true
#cp -r /usr/local/share/ca-certificates/* "$CHROOTDIR/usr/local/share/ca-certificates" || true

mount -t proc proc "$CHROOTDIR/proc"
mount -t sysfs sysfs "$CHROOTDIR/sys"

# Required for some warning messages about writing to log files
mount --bind /dev/pts "$CHROOTDIR/dev/pts"

# Prevent perl locale warnings in the chroot:
export LC_ALL=C

[ -n "$INTERACTIVE" ] && echo "Entering chroot in '$CHROOTDIR'."

if [ -n "$INTERACTIVE" ]; then
	chroot "$CHROOTDIR"
else
	chroot "$CHROOTDIR" /bin/sh -c "$*"
fi

umount "$CHROOTDIR/dev/pts"
umount "$CHROOTDIR/sys"
umount "$CHROOTDIR/proc"

[ -n "$INTERACTIVE" ] && echo "Exited chroot in '$CHROOTDIR'."
exit 0
